const { path, fs, getMatchingFolderPath } = require('../scripts/common.js');

// 心得相关功能
document.getElementById('experienceLabel').onclick = async () => {
    const fileList = document.getElementById('fileList');
    const fileContent = document.getElementById('fileContent');
    const card4 = document.querySelector('.card-4');
    
    // 清空内容
    fileContent.innerHTML = '';
    card4.innerHTML = '';
    
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (!matchingFolderPath) {
            fileList.innerHTML = '<div class="file-item">未找到匹配的文件夹</div>';
            return;
        }

        const thoughtsPath = path.join(matchingFolderPath, 'thoughts');
        if (!fs.existsSync(thoughtsPath)) {
            fileList.innerHTML = '<div class="file-item">thoughts文件夹不存在</div>';
            return;
        }

        // 读取thoughts文件夹下的所有JSON文件
        const files = fs.readdirSync(thoughtsPath)
            .filter(file => file.endsWith('.json'))
            .map(file => ({
                name: file,
                path: path.join(thoughtsPath, file)
            }));

        if (files.length === 0) {
            fileList.innerHTML = '<div class="file-item">没有找到JSON文件</div>';
            return;
        }

        // 显示文件列表
        fileList.innerHTML = '';
        files.forEach(file => {
            const div = document.createElement('div');
            div.className = 'file-item';
            div.textContent = file.name;
            div.onclick = () => showQuestions(file.path);
            fileList.appendChild(div);
        });
    } catch (error) {
        console.error('Error:', error);
        fileList.innerHTML = '读取文件失败：' + error.message;
    }
};

// 获取项目步骤描述
async function getStepDescription(projectName, stepNumber) {
    try {
        const matchingFolderPath = getMatchingFolderPath();
        if (!matchingFolderPath) return null;

        const projectsPath = path.join(matchingFolderPath, 'projects');
        const files = fs.readdirSync(projectsPath);
        
        // 查找匹配的项目文件
        const projectFile = files.find(file => file.endsWith(`_${projectName}`));
        if (!projectFile) return null;

        const projectContent = fs.readFileSync(path.join(projectsPath, projectFile), 'utf8');
        const projectData = JSON.parse(projectContent);

        // 查找匹配的步骤
        const step = projectData.steps.find(s => s.stepNumber === stepNumber);
        return step ? step.description : null;
    } catch (error) {
        console.error('Error getting step description:', error);
        return null;
    }
}

// 显示问题列表
async function showQuestions(filePath) {
    const fileContent = document.getElementById('fileContent');
    try {
        const content = fs.readFileSync(filePath, 'utf8');
        const data = JSON.parse(content);
        const projectName = path.basename(filePath, '.json');
        
        // 分类问题
        const unfinished = data.filter(q => q.status === 'unsolved');
        const finished = data.filter(q => q.status === 'solved');

        // 显示问题列表
        fileContent.innerHTML = `
            <div class="questions-container">
                <div class="questions-section">
                    <h3>未解决 (${unfinished.length})</h3>
                    <div class="questions-list" id="unfinishedList"></div>
                </div>
                <div class="questions-section">
                    <h3>已解决 (${finished.length})</h3>
                    <div class="questions-list" id="finishedList"></div>
                </div>
            </div>
        `;

        // 添加未完成问题
        const unfinishedList = document.getElementById('unfinishedList');
        unfinished.forEach(question => {
            const div = document.createElement('div');
            div.className = 'question-item';
            div.textContent = question.problem;
            div.onclick = () => showQuestionDetail(question, projectName);
            unfinishedList.appendChild(div);
        });

        // 添加已完成问题
        const finishedList = document.getElementById('finishedList');
        finished.forEach(question => {
            const div = document.createElement('div');
            div.className = 'question-item completed';
            div.textContent = question.problem;
            div.onclick = () => showQuestionDetail(question, projectName);
            finishedList.appendChild(div);
        });

        // 更新选中状态
        document.querySelectorAll('.file-item').forEach(item => {
            item.classList.remove('selected');
            if (item.textContent === path.basename(filePath)) {
                item.classList.add('selected');
            }
        });
    } catch (error) {
        console.error('Error:', error);
        fileContent.innerHTML = '读取问题失败：' + error.message;
    }
}

// 添加时间格式转换函数
function formatTimestamp(timestamp) {
    const year = timestamp.substring(0, 4);
    const month = timestamp.substring(4, 6);
    const day = timestamp.substring(6, 8);
    const hour = timestamp.substring(8, 10);
    const minute = timestamp.substring(10, 12);
    
    return `${year}年${parseInt(month)}月${parseInt(day)}日${hour}:${minute}`;
}

// 修改显示问题详情函数中的时间显示部分
async function showQuestionDetail(question, projectName) {
    const card4 = document.querySelector('.card-4');
    
    // 获取步骤描述
    const stepDescription = await getStepDescription(projectName, question.step);
    
    card4.innerHTML = `
        <div class="question-detail">
            <h3>${question.status === 'solved' ? '已解决' : '未解决'}</h3>
            <p class="project-name">${projectName}</p>
            ${stepDescription ? `<p class="step-description">步骤${question.step}：${stepDescription}</p>` : ''}
            <p class="problem">问题：${question.problem}</p>
            ${question.status === 'solved' 
                ? `<p class="solution">成功方案：${question.solution}</p>`
                : `<p class="deadend">不通的路：${question.deadend}</p>`
            }
            <div class="question-meta">
                <span>时间: ${formatTimestamp(question.timestamp)}</span>
            </div>
        </div>
    `;

    // 更新选中状态
    document.querySelectorAll('.question-item').forEach(item => {
        item.classList.remove('selected');
        if (item.textContent === question.problem) {
            item.classList.add('selected');
        }
    });
}

module.exports = {}; 